var show_num = [];


$(function(){
    // 初次进入判断是否登陆过 登陆过直接跳转首页
    if(loginType()){
        draw(show_num);
        $("#canvas").on('click',function(){
            draw(show_num);
        })
    }else {
        window.location.href = "./index.html"
    }

})

function loginType() {
    try {
        //运行代码
        var user = localStorage.getItem('user');
        var ggNicheng = JSON.parse(user).ggNicheng
        console.log(ggNicheng)
        if(ggNicheng == "" || ggNicheng == null || ggNicheng == undefined){
            return true
        }else {
            return false
        }
    } catch(err) {
        //处理错误
        return true
    }
}

function login() {
    var usernames = $('input[name="username"]').val();
    var passwords = $('input[name="password"]').val();

    //判断验证码是否正确和为空
    var val = $("#verification").val().toLowerCase();
    var num = show_num.join("");
    if(val==''){
        layer.msg('请输入验证码！', {
            btn: '确定',
            btnAlign: 'c'
        });
        $("#error_login").html('');
        return
    }else if(val != num){
        layer.msg('验证码错误！请重新输入！', {
            time:0,
            btn: '确定',
            btnAlign: 'c'
        });
        $("#verification").val('');
        $("#error_login").html('');
        draw(show_num);
        return
    }
    //判断是否为空
    if(usernames.length<=0 || passwords<=0) {
        layer.msg('账号密码不能为空请重新输入！', {
            time:0,
            btn: '确定',
            btnAlign: 'c'
        });
        $("#error_login").html('');
        return
    }
    $.ajax({
        type: 'POST',
        url: "/login",
        data: {
            name:usernames,
            password: Base64.encode(passwords)
        },
        success: function (message) {
            if(message.code==0){
                localStorage.setItem("user",JSON.stringify(message.data))
                window.location.href = "./index.html"
            }else {
                // $("#error_login").html('');
                // $("#error_login").append(message.message);
                layer.msg(message.message, {
                    time:0,
                    btn: '确定',
                    btnAlign: 'c'
                });
                $("#verification").val('');
                $("#error_login").html('');
                draw(show_num);
                return
            }
        },
        error: function (message) {
            layer.msg('服务器出问题了，请稍后重试！', {
                time:0,
                btn: '确定',
                btnAlign: 'c'
            });
            $("#error_login").html('');
            return
        }
    })
}

document.onkeydown = function (e) { // 回车提交表单
    // 兼容FF和IE和Opera
    var theEvent = window.event || e;
    var code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code == 13) {
        login();
    }
}

function draw(show_num) {
    var canvas_width=$('#canvas').width();
    var canvas_height=$('#canvas').height();
    var canvas = document.getElementById("canvas");//获取到canvas的对象，演员
    var context = canvas.getContext("2d");//获取到canvas画图的环境，演员表演的舞台
    canvas.width = canvas_width;
    canvas.height = canvas_height;
    var sCode = "A,B,C,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
    var aCode = sCode.split(",");
    var aLength = aCode.length;//获取到数组的长度

    for (var i = 0; i <= 3; i++) {
        var j = Math.floor(Math.random() * aLength);//获取到随机的索引值
        var deg = Math.random() * 30 * Math.PI / 180;//产生0~30之间的随机弧度
        var txt = aCode[j];//得到随机的一个内容
        show_num[i] = txt.toLowerCase();
        var x = 10 + i * 20;//文字在canvas上的x坐标
        var y = 20 + Math.random() * 8;//文字在canvas上的y坐标
        context.font = "bold 23px 微软雅黑";

        context.translate(x, y);
        context.rotate(deg);

        context.fillStyle = randomColor();
        context.fillText(txt, 0, 0);

        context.rotate(-deg);
        context.translate(-x, -y);
    }
    for (var i = 0; i <= 5; i++) { //验证码上显示线条
        context.strokeStyle = randomColor();
        context.beginPath();
        context.moveTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.lineTo(Math.random() * canvas_width, Math.random() * canvas_height);
        context.stroke();
    }
    for (var i = 0; i <= 30; i++) { //验证码上显示小点
        context.strokeStyle = randomColor();
        context.beginPath();
        var x = Math.random() * canvas_width;
        var y = Math.random() * canvas_height;
        context.moveTo(x, y);
        context.lineTo(x + 1, y + 1);
        context.stroke();
    }
}

function randomColor() {//得到随机的颜色值
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);
    return "rgb(" + r + "," + g + "," + b + ")";
}

/**
 * 封装一个居中打开新窗口的方法
 */
function openWindow(url, width, height)
{
    width = width || 600;
    height = height || 400;
    var left = (window.screen.width - width) / 2;
    var top = (window.screen.height - height) / 2;
    window.open(url, "_blank", "toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, left="+left+", top="+top+", width="+width+", height="+height);
}

function qqLogin()
{
    var qqAppId = '424323422'; // 上面申请得到的appid
    var qqAuthPath = 'http://www.test.com/auth'; // 前面设置的回调地址
    var state = 'fjdslfjsdlkfd'; // 防止CSRF攻击的随机参数，必传，登录成功之后会回传，最好后台自己生成然后校验合法性
    openWindow(`https://graph.qq.com/oauth2.0/authorize?response_type=token&client_id=${qqAppId}&redirect_uri=${encodeURIComponent(qqAuthPath)}&state=${state}`);
}